import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { UserInfo } from '@/types'
import { authApi } from '@/api'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string>('')
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)

  // 从localStorage初始化状态
  const initFromStorage = () => {
    const storedToken = localStorage.getItem('pdx_token')
    const storedUserInfo = localStorage.getItem('user_info')
    
    if (storedToken) {
      token.value = storedToken
    }
    
    if (storedUserInfo) {
      try {
        userInfo.value = JSON.parse(storedUserInfo)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        localStorage.removeItem('user_info')
      }
    }
  }

  // 登录
  const login = async (username: string, password: string) => {
    try {
      const response = await authApi.login({ username, password })
      const { userInfo: user, token: userToken } = response.data
      
      // 保存到状态
      userInfo.value = user
      token.value = userToken
      
      // 保存到localStorage
      localStorage.setItem('pdx_token', userToken)
      localStorage.setItem('user_info', JSON.stringify(user))
      
      return response
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (userInfo.value?.username) {
        await authApi.logout(userInfo.value.username)
      }
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除状态和localStorage
      userInfo.value = null
      token.value = ''
      localStorage.removeItem('pdx_token')
      localStorage.removeItem('user_info')
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await authApi.getProfile()
      userInfo.value = response.data
      localStorage.setItem('user_info', JSON.stringify(response.data))
      return response
    } catch (error) {
      throw error
    }
  }

  // 检查登录状态
  const checkLoginStatus = async () => {
    try {
      await authApi.isLogin()
      return true
    } catch (error) {
      // 如果检查失败，清除本地状态
      logout()
      return false
    }
  }

  // 更新用户信息
  const updateUserInfo = (newUserInfo: Partial<UserInfo>) => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...newUserInfo }
      localStorage.setItem('user_info', JSON.stringify(userInfo.value))
    }
  }

  // 初始化
  initFromStorage()

  return {
    userInfo,
    token,
    isLoggedIn,
    login,
    logout,
    fetchUserInfo,
    checkLoginStatus,
    updateUserInfo
  }
})
